package com.cloud.phone.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.app.DownloadManager
import android.content.Context.DOWNLOAD_SERVICE
import android.net.Uri
import android.os.Environment
import android.os.Handler
import android.os.Looper
import com.blankj.utilcode.util.LogUtils
import com.cloud.phone.manager.FileManager
import java.io.File


/**
 * @auth: njb
 * @date: 2024/6/26 15:04
 * @desc: 文件下载工具类
 */
object DownLoadUtils {
    private val TAG = "DownLoadUtils"

    val handler = Handler(Looper.getMainLooper())
    fun downLoadApk(apkUrl: String, context: Activity) {
        LogUtils.d(TAG, "===apk下载链接为===$apkUrl")
        //TsUtils.showTips("===apk正在下载中。。。===")
        //创建request对象
        val request: DownloadManager.Request =
            DownloadManager.Request(Uri.parse(apkUrl))
        //下载完成后通知显示还是隐藏
        //request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN)
        //设置通知栏的标题
        request.setTitle("版本更新")
        //设置通知栏的message
        request.setDescription("正在下载.....")
        //设置下载文件类型
        request.setMimeType("application/vnd.android.package-archive")
        //设置文件存放目录
        request.setDestinationInExternalFilesDir(
            context,
            Environment.DIRECTORY_DOWNLOADS,FileManager.DOWNLOAD_APK_PATH
        )
        //获取系统服务
        val downloadManager = context.getSystemService(DOWNLOAD_SERVICE) as DownloadManager
        try {
            //进行下载
            val id = downloadManager.enqueue(request)
            val runnable = object : Runnable {
                @SuppressLint("Range")
                override fun run() {
                    val cursor = downloadManager.query(DownloadManager.Query().setFilterById(id))
                    cursor?.apply {
                        if (moveToFirst()) {
                            val title =
                                getString(getColumnIndex(DownloadManager.COLUMN_TITLE))
                            val uri =
                                getString(getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
                            val current =
                                getInt(getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                            val total =
                                getInt(getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))
                            LogUtils.e(TAG,current.toString())
                            //获取下载状态信息
                            if (getInt(getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                                //下载完成
                                handler.removeCallbacksAndMessages(null)
                                LogUtils.e("下载完成：${Uri.parse(uri).path.toString()}")
                                val file = File(Uri.parse(uri).path.toString())
                                //下载完成开始安装apk
                                RootUtils.rootInstallApk(file)
                            }
                        }
                    }
                    cursor?.close()
                    handler.postDelayed(this, 1000)
                }
            }
            handler.postDelayed(runnable, 1000)
        } catch (e: Exception) {
            e.printStackTrace()
            LogUtils.e(TAG,"===下载apk出错==="+e.message)
            //下载完成
            handler.removeCallbacksAndMessages(null)
        }
    }
}